package com.jd.dl.util;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.log4j.Logger;



import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class TemplateUtil {
	private static Logger log = Logger.getLogger(TemplateUtil.class);
	private static String DEFAULT_ENCODING="UTF-8";
	private static Map<String,Template> templateCache = new ConcurrentHashMap<String,Template>();
	
	/**
	 * @function 根据名称查找模板
	 * @param templateName 模板名称
	 *
	 * @return
	 * @exception
	 *
	 * @author 
	 * @history
	 */
	private static Template getTemplate(String templateName, boolean cache) {
		Template template = templateCache.get(templateName);
		if(template==null){
			try {
				String path = FileUtil.getFilePath(templateName);
				String name = FileUtil.getFileName(templateName);
				// 获取模板
				Configuration config = new Configuration();
				config.setDirectoryForTemplateLoading(new File(path));
				template = config.getTemplate(name, DEFAULT_ENCODING);
			} catch (IOException e) {
				log.error(e);
				e.printStackTrace();
			}
		}
		
		//缓存模板
		if (cache){
			templateCache.put(templateName, template);
		}
		
		return template;
	}

	/**
	 * @function 用数据填充模板并返回渲染结果
	 * @param templateName 模板名称
	 * @param rootMap 数据
	 *
	 * @return 渲染结果
	 * @exception
	 *
	 * @author 
	 * @history
	 *
	 */
	public static String process(String templateName, Map<String, ? extends Object> rootMap, boolean cache) {
		StringWriter writer = new StringWriter();
		StringBuffer buffer = new StringBuffer();
		Template template = getTemplate(templateName, cache);
		if(template!=null){
			try {
				template.setEncoding(DEFAULT_ENCODING);
				template.process(rootMap, writer);
				writer.flush();
				buffer = writer.getBuffer();
			} catch (TemplateException e) {
				log.error(e);
			} catch (IOException e) {
				log.error(e);
			}
		}
		
		return buffer.toString();
	}
	
	public static String process(String templateName, Map<String, ? extends Object> rootMap) {
		return process(templateName, rootMap, false);
	}
}
